const widgets = require('widget');
const data = require('self').data;
const pageMod = require('page-mod');
const panels = require('panel');
const ss = require('simple-storage');
const tabs = require('tabs');
const pageWorkers = require("page-worker");
const req = require('request').Request;

var workers = new Array(), widget, url, pattern = /http:\/\/(.*)\.minitroopers.fr\/hq/;

if (!ss.storage.armees)
    ss.storage.armees = new Array();

function detachWorker(worker, workerArray) {
    var index = workerArray.indexOf(worker);
    if(index != -1) {
        workerArray.splice(index, 1);
    }
}

function Armee(pseudo, saved){
    this.pseudo = pseudo;
    this.saved = saved;
}

function InitWidget(){
	widget = widgets.Widget({
        id: "MTManager",
        label: "Minitroopers Manager",
        contentURL: data.url('widget.png'),
        contentScriptWhen: 'ready',
		toolTip: 'Mes armées',
        onClick: ShowArmees
    });
}

function InitPageMod(){
	pageMod.PageMod({
        include: [pattern],
        contentScriptWhen: 'ready',
        contentScriptFile: [data.url('jquery.js'),data.url('application.js')],
        onAttach: function(worker) {
            workers.push(worker);
            worker.on('detach', function () {
                detachWorker(this, workers);
            });
			/*
			worker.port.on('LoadBattle', function(url){
				console.debug('load battle : '+url);
				pageWorkers.Page({
		            contentURL: url,
		            contentScriptWhen: "end",
		            contentScriptFile: [data.url('jquery.js'),data.url('battle.js')],
		            onMessage: function(data) {
						console.debug('battle loaded');
						worker.port.emit('BattleLoaded', data);
		                this.destroy();
		            }
		        });
			});
			*/
        }
    });
}

function ListenTabs(){
	tabs.on('activate', function(tab) {
		console.log('activate : ' + tab.url);
		TestTab(tab);
	});
	tabs.on('open', function(tab){
		console.log('open : ' + tab.url);
		tab.on('ready', function(tab){
			console.log('ready : ' + tab.url);
			TestTab(tab);
		});
	});
}

function TestTab(tab){
	widget.contentURL = data.url('widget.png');
	widget.tooltip = 'Mes armées';
	if(pattern.test(tab.url)){
        var match = pattern.exec(tab.url)[1];
        var index = ss.storage.armees.indexOf(match);
		console.log('match : '+match+' ('+index+')');
        if(index == -1){
			console.log('blink');
            widget.contentURL = data.url('widget-blink.gif');
			widget.tooltip = 'Ajouter une armée';
        }
    }
}

function ShowArmees(){
    var panel = panels.Panel({
        contentURL: data.url('armees.html'),
        contentScriptWhen: 'ready',
        contentScriptFile: [data.url('jquery.js'),data.url('armees.js')],
        onShow: function() {
            var armees = new Array();
            
            ss.storage.armees.forEach(function(armee){
                armees.push(new Armee(armee, true));
            });
            
			for(var i=0;i<tabs.length;i++){
                if(pattern.test(tabs[i].url)){
                    var match = pattern.exec(tabs[i].url)[1];
                    var index = ss.storage.armees.indexOf(match);
                    if(index == -1){
                        armees.push(new Armee(match, false));
                    }
                }
            }            
            this.postMessage(armees);
        },
        onMessage: function(armee) {
            var index = ss.storage.armees.indexOf(armee);
            if(index == -1){
                ss.storage.armees.push(armee);
            }
            else{
                tabs.activeTab.url = 'http://'+armee+'.minitroopers.fr/hq';
            }
            this.hide();
        }
    });
    
    panel.show();
}

function GetId(){
	pageWorkers.Page({
		contentURL: 'http://minitroopers.fr/',
		contentScriptWhen: 'end',
		contentScriptFile: [data.url('jquery.js'),data.url('create.js')],
		onMessage: function(id) {
			ss.storage.id = id;
			this.destroy();
			GetUrl(id);
		}
	});
}

function GetUrl(id){
	req({
		url: url,
		content:'id='+id,
		onComplete: function (response) {
			if(response.json){
				pageWorkers.Page({
					contentURL: response.json.url,
					contentScriptWhen: "end",
					contentScriptFile: [data.url('jquery.js'),data.url('create.js')],
					onMessage: function() {
						this.postMessage(response.json);
					}
				});	
			}
		}
	}).get();
}

exports.main = function(options, callbacks) {
    InitWidget();
    InitPageMod();
    ListenTabs();
	
	url = options.staticArgs.url;	
	if(!ss.storage.id)
		GetId();
	else
		GetUrl(ss.storage.id);    
};




